<template class="parent">
  <div class="child" style="height: 100%">
    <el-container style="margin-right: 700px">
      <el-upload :action= ip :limit="3" :data={selectIndex:state.nextPath} :on-success="handleUploadSuccess">
        <el-button type="primary" style="font-size: 20px"><el-icon><CirclePlus /></el-icon>上传文件 <i class="el-icon-circle-plus-outline"></i></el-button>
      </el-upload>
      <el-button type="warning" @click="addfold" style="font-size: 20px"><el-icon><FolderAdd /></el-icon>新建文件夹 <i class="el-icon-circle-plus-outline"></i></el-button>
      <el-button type="success" @click="upStep" style="font-size: 20px; margin-left: 0px"><el-icon><House /></el-icon>返回首页</el-button>
    </el-container>
    <el-table :data="filterTableData" style="font-size: 20px;width:100%;height: 100%" :row-style="{height: '20px'}" :cell-style="{padding:'0px'}"
              scrollbar-always-on="true"
              flexible="true"
              size="large"
    >

      <el-table-column label="文件类型" prop="type" >
        <template v-slot="scope">
          <h2 v-if="scope.row.type === 1"><el-icon><DocumentCopy /></el-icon></h2>
          <h2 v-if="scope.row.type === 2"><el-icon><Folder /></el-icon></h2>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="creatTime" />
      <el-table-column label="文件名" prop="filename" show-overflow-tooltip="true"  />
      <el-table-column label="文件大小" prop="size" />
      <el-table-column align="right">
        <template #header>
          <el-input v-model="search" size="large" placeholder="请输入文件名" />
        </template>
        <!--        <template #default="scope">-->
        <template v-slot="scope">
          <el-button size="large" @click="down(scope.row.filename, scope.row.path)" type="success" v-if="scope.row.type === 1"
          ><el-icon><Files /></el-icon>下载</el-button
          >
          <el-button size="large" @click="open(scope.row.filename)" type="primary" v-if="scope.row.type === 2"><el-icon><Folder /></el-icon>打开</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--    创建文件夹-->
    <el-dialog v-model="dialogFormVisible" title="创建文件夹" :modal="false" width="40%">
      <el-form :model="state.form" :rules="state.rules" ref="ruleFormRef" style="width: 85%" label-width="120px">
        <el-form-item label="文件名"  prop="status">
          <el-input  v-model="state.form.filename" autocomplete="off" placeholder="请输入文件夹名称"/>
        </el-form-item>
        <!--        <el-form-item label="文件路径"  prop="status">-->
        <!--          <el-input  v-model="state.form.path" autocomplete="off" placeholder="如 /home/userfile/file"/>-->
        <!--        </el-form-item>-->
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="save">
          创建
        </el-button>
      </span>
      </template>
    </el-dialog>

  </div>
</template>

<script lang="ts" setup>
import {computed, onMounted, reactive, ref, getCurrentInstance } from 'vue'
import {Folder, CirclePlus,House,DocumentCopy,FolderAdd,Files} from '@element-plus/icons-vue'
import {ElNotification} from "element-plus";
import request from "../request.js";
import router from "../router/index.js";

const ip = getCurrentInstance()?.appContext.config.globalProperties.$ip + "/upload"

// interface User {
//   date: string
//   name: string
//   address: string
// }
interface Files{
  creatTime: string
  filename: string
  size: string
}
const state = reactive({
  form:{},
  down:{},
  // nextPath:"/", ///opt/file
  // upPath:"/",
  path:sessionStorage.getItem('path'),
  nextPath:sessionStorage.getItem('path'), ///opt/file
  upPath:sessionStorage.getItem('path'),
  username:sessionStorage.getItem('username'),
  temp:"",
})

const currentPage = ref(1)
const pageSize = ref(1)
const total = ref(0)
const search = ref('')

const dialogFormVisible = ref(false)
const dialogVisible = ref(false)
const dia = ref(false)
const name = ref(null)

const addfold = () => {
  state.form.path = state.nextPath //初始化数据
  dialogFormVisible.value = true
}
const tableData = reactive({
  Files:{}
})




const load = () => {
  if(state.username == null){
    console.log("name "+state.username + "ip"+ ip)
    ElNotification.error("请先登录")
    router.push("/")
  } else {
    console.log(state.username, state.nextPath, ip)
    request.get("/openFolder", {
      params: {
        path: state.path
      }
    }).then(res=>{
      if(res==false){
        ElNotification.error("文件列表中包含空格")
      }else{
        tableData.Files = res;
        console.log(tableData.Files)
      }
    })
  }
}
load()
const filterTableData = computed(() =>
    tableData.Files.filter(
        (data) =>
            !search.value ||
            data.filename.toLowerCase().includes(search.value.toLowerCase())
    )
)


// const handleEdit = (index: number, row: User) => {
//   console.log(index, row)
// }

const handleSizeChange = (val) => {
  pageSize.value = val
}
const handleCurrentChange = (val) => {
  currentPage.value = val
}
const handleUploadSuccess = (res) => {
  console.log(res)
  if(res == true){
    ElNotification.success("上传成功")
    //不返回首页
    request.get("/openFolder", {
      params:{
        path: state.nextPath
      }
    }).then(res=>{
      if(res==false){
        ElNotification.error("文件列表包含空格无法打开")
      }else {
        tableData.Files = res;
      }
      //console.log(tableData.Files)
    })
  }else {
    ElNotification.error("上传失败注意文件不可有空格！")
  }
}
// const fuGai = () => {
//
// }

const handleAddFile = (filename) => {
  //name.value = filename
  state.down.filename = filename
  dialogVisible.value=true
}

const save = () => {
  state.form.path = state.nextPath
  request.put("/addFolder", state.form).then(res=>{
    if(res == true){
      ElNotification.success("创建成功")
      //load()
      //不返回首页
      request.get("/openFolder", {
        params:{
          path: state.nextPath
        }
      }).then(res=>{
        tableData.Files = res;
        //console.log(tableData.Files)
      })

    }else ElNotification.error("创建失败，同名，有空格或权限不够")
  })
  dialogFormVisible.value = false
}

const open = (foldername) => {
  state.temp = state.nextPath
  //console.log("temp0 "+state.temp)
  state.nextPath =state.nextPath+"/"+foldername;
  //console.log(state.nextPath)
  request.get("/openFolder", {
    params:{
      path: state.nextPath
    }
  }).then(res=>{
      tableData.Files = res;

    //console.log("temp 1"+state.temp+" "+res)
    //console.log("res "+tableData.Files)
  }).catch(onerror=>{
    state.nextPath = state.temp
    ElNotification.error("文件列表有误，查询超时!!!")
    //console.log("res2")
  })
}
const down = (filename, path) => {
  request.get("/download", {
    responseType: 'blob',
    params:{
      file: filename,
      path: path
    }
  }).then(res=>{
    console.log(res)
    /* global window */
    const url = window.URL.createObjectURL(new Blob([res]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    link.click();
    ElNotification.success("下载开始，请检查浏览器下载列表")
  }).catch(err=>{
    ElNotification.error(err + " cuow")
  })
}

const upStep = () => {
  //console.log("点击返回 ")
  request.get("/openFolder", {
    params:{
      path: state.upPath
    }
  }).then(res=>{
    tableData.Files = res;
    state.nextPath=state.upPath
    //console.log(tableData.Files)
  }).catch(err=>{
    ElNotification.error("网络拥堵")
  })
}

</script>
<style>
.child {
  position:absolute;
  left:50%;
  transform:translateX(-50%);
}
.parent {
  position:relative;
}
/**修改全局的滚动条*/
/**滚动条的宽度*/

.el-scrollbar__thumb{
  background-color: red;
  width: max-content;
}

</style>
